<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>上传数据</title>
        <link rel="stylesheet" type="text/css" href="/webapp/css/easyui.css">
        <link rel="stylesheet" type="text/css" href="/webapp/css/icon.css">
        <link rel="stylesheet" type="text/css" href="/webapp/css/color.css">
        <link rel="stylesheet" type="text/css" href="/webapp/css/public.css">
        <script type="text/javascript" src="/webapp/js/lib/jquery.min.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/jquery.easyui.min.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/jquery.global.settings.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/aliyun-oss-sdk.min.js"></script>
        <script type="text/javascript" src="/webapp/js/common/config.js"></script>
    </head>
    <body>
        <div class="easyui-container-fluid" style="border:none;">
            <div class="easyui-panel" style="border:none;">
                <div class="nav" id="nav"></div>
                <div class="easyui-panel" style="border:none;">
                    <form id="ff">
                        <div style="margin-bottom: 20px;">
                            <label class="item-label">渠道：</label>
                            <input type="text" id="channel" name="channelName" class="easyui-textbox" disabled="disabled" style="width: 100px"/>
                            <label class="item-label">年：</label>
                            <input type="text" id="year" name="reportYear" class="easyui-textbox" disabled="disabled" style="width: 100px"/>
                            <span id="monthSpan">
						   		<label class="item-label">月：</label>
						   		<input type="text" id="month" name="reportMonth" class="easyui-textbox" disabled="disabled" style="width: 100px"/>
						   </span>
                            <span id="weekSpan">
							    <label class="item-label">周：</label>
						   		<input type="text" id="week" name="reportWeek" class="easyui-textbox" disabled="disabled" style="width: 100px"/>
						   </span>
                            <label class="item-label">导入状态：</label>
                            <select class="easyui-combobox" name="status" data-options="panelHeight:'auto'" style="width: 100px">
                                <option value="">--请选择--</option>
                                <option value="WAITING">待导入</option>
                                <option value="RUNNING">分析中</option>
                                <option value="FAIL">导入失败</option>
                                <option value="SUCCESS">导入成功</option>
                            </select>
                            <a href="javascript:void(0);" style="width:80px;margin-left:40px;" class="easyui-linkbutton c8" onclick="searchBy()">查询</a>
                        </div>
                    </form>
                </div>
                <div class="table-wrapper"><!--singleSelect:true,-->
                    <table id="datagrid" class="easyui-datagrid" data-options="fitColumns:true,scrollbarSize:0,checkOnSelect:false">
                        <thead>
                            <tr>
                                <th data-options="field:'id',checkbox:true,align:'center'"></th>
                                <th data-options="field:'code',align:'center'" width="40">文件批号</th>
                                <th data-options="field:'template.name',align:'center',formatter:templateFormatter" width="40">模版</th>
                                <th data-options="field:'filePath',align:'center'," width="40">文件名称</th>
                                <th data-options="field:'createDate',align:'center'" width="30">上传日期</th>
                                <th data-options="field:'updateTime',align:'center'" width="50">修改日期</th>
                                <th data-options="field:'status',align:'center',formatter:importStatusFormatter" width="40">导入状态</th>
                                <th data-options="field:'dataCount',align:'center'" width="20">数据条数</th>
                                <th data-options="field:'username',align:'center'" width="30">上传人</th>
                                <th data-options="field:'action',formatter:actions,align:'center'" width="250">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div id="dd" class="easyui-window upload-wrapper" title="禁用空型号" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:330px;height:220px;padding:10px;">
            <span class="item-required">*注意：请慎选品类数据会被删除</span>
            <div class='box' style="margin-bottom:20px">
                批号： <input type="text" id="uploadRecordCode" name="uploadRecordCode" class="easyui-textbox" disabled="disabled" data-options="" style="width:200px;"/></div>
            <div class='box' style="margin-bottom:20px">
                品类：
                <select id="categoryList" class="easyui-combobox" style="width:200px;" name="categories" data-options="multiple:true"></select>

            </div>

            <div style="text-align:center">
                <a style="width:60px;height: 30px;" href="javascript:void(0);" class="easyui-linkbutton c8" onclick="removeCa()">保存</a>
            </div>
        </div>
        <div id="w" class="easyui-window upload-wrapper" title="上传文件" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:400px;height:320px;padding:10px;">
            <form id="window-form">
                <div style="margin-bottom:20px;">
                    <label class="item-label">选择模版：</label>
                    <select id="template" name="templateCode" style="width:230px;"></select>
                </div>
                <div style="margin-bottom:20px;">
                    <label class="item-label">选择文件：</label>
                    <input id="upload" multiple="multiple" style="width:230px;"/>
                </div>
                <div style="margin-bottom:20px;">
                    <label class="item-label">上传版本：</label>
                    <select id="uploadVersion" class="easyui-combobox" style="width:230px;">
                        <option value="4">version4.0</option>
                        <option value="3">version3.0</option>
                        <option value="2">version2.0</option>
                        <option value="1">version1.0</option>
                    </select>
                </div>
                <div style="margin-bottom:20px;">
                    <label class="item-label">数据类型：</label>
                    <select id="fileType" class="easyui-combobox" style="width:230px;">
                        <option value="1">常规品类</option>
                        <option value="2">3C产品</option>
                    </select>
                </div>
                    <!--<div style="margin-bottom:20px;">-->
                    <!--<label class="item-label">是否校验日期：</label>-->
                    <!--<select name="checkDate" class="easyui-combobox" style="width:230px;">-->
                        <!--<option value="false">否</option>-->
                        <!--<option value="true">是</option>-->
                    <!--</select>-->
                <!--</div>-->
                <div style="margin-bottom:20px;text-align:center">
                    <a style="width:80px;" href="javascript:void(0);" class="easyui-linkbutton c8" onclick="upload()">保存</a>
                </div>
            </form>
        </div>
        <div id="m" class="easyui-window" title="导入结果" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:400px;height:260px;padding:10px;">
            <h3>定位错误行：</h3>
            <div id="errorIndex"></div>
            <h3>未知商场：</h3>
            <div id="content"></div>
            <h3>识别异常：</h3>
            <div id="warnStatus"></div>
            <h3>时间异常行：</h3>
            <div id="dateErrorIndex"></div>
        </div>
        <script type="text/javascript">
            var id;
            var channelCode;
            var dataReportCode;
            initCategorySelect("categoryList")
            $(function () {
                id = getQueryParameter("id");
                setNav();
                $("#datagrid").datagrid({
                    pagination: true,
                    rownumbers: true,
                    checkOnSelect: false,
                    toolbar: [{
                        text: "上传",
                        handler: function () {
                            selectFile();
                        }
                    },'-',{
                        text: "去重",
                        handler: function () {
                            tmReRepeat();
                        }
                    }],
                    onBeforeSelect: function () {
                        return false;
                    }
                }).datagrid("getPager").pagination({
                    onSelectPage: searchBy
                });
                $.when(initPage()).done(searchBy);
            });

            function initPage() {
                var dtd = $.Deferred();
                if (isMonthType()) {
                    $("#weekSpan").remove();
                } else {
                    $("#monthSpan").remove();
                }
                $.ajax({
                    url: config.url + "/dataReport/" + id,
                    xhrFields: {withCredentials: true},
                    success: function (data) {
                        if (data) {
                            channelCode = data.channelCode;
                            dataReportCode = data.code;
                            $("#ff").form("load", data);
                            dtd.resolve();
                        }
                    },
                    error: function (data) {
                        console.log(data);
                        dtd.reject();
                    }
                });
                return dtd.promise();
            }

            function actions(val, row) {
                return "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    "style='width:16%;' onclick='showResult(\"" + row.id + "\")'>查看导入结果</a>&nbsp;" +
                    // "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    // "style='width:60px;' onclick='stopImport(\"" + row.id + "\")'>停止</a>&nbsp;" +
                    "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    "style='width:10%;' onclick='retryDate(\"" + row.code + "\")'>日期识别</a>&nbsp;" +
                    "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    "style='width:10%;' onclick='cancelWarn(\"" + row.code + "\")'>撤销异常</a>&nbsp;" +
                    "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    "style='width:6%;' onclick='disableOne(\"" + row.id + "\")'>删除</a>&nbsp;" +
                    "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    "style='width:14%;' onclick='importAgain(\"" + row.id + "\")'>分析未匹配</a>&nbsp;" +
                    "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    "style='width:10%;' onclick='downloadFile(\"" + row.id + "\")'>下载文件</a>&nbsp;" +
                    // "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    // "style='width:10%;' onclick='reImport(\"" + row.id + "\")'>重新导入</a>&nbsp;" +
                    "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                    "style='width:10%;' onclick='analysisReturn(\"" + row.id + "\")'>分析退货</a>&nbsp;"+
                    "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' " +
                "style='width:10%;' onclick='dd(\"" + row.code + "\")'>错误品类</a>";
            }

            //查看导入结果
            function showResult(id) {
                $("#m").window("open");
                $("#errorIndex").text("正在查询中...");
                $("#content").text("正在查询中...");
                $.ajax({
                    url: config.url + "/uploadRecord/importResult/" + id,
                    type: "get",
                    xhrFields: {withCredentials: true},
                    success: function (data) {
                        if (data.code == 200) {
                            $("#errorIndex").text(data.data["errorIndex"]);
                            $("#warnStatus").text(data.data["warnStatus"]);
                            $("#dateErrorIndex").text(data.data["dateErrorIndex"]);

                            var html = "";
                            var content = data.data["content"];
                            $.each(content, function (i, m) {
                                html += '<div>' + m + '</div>';
                            })
                            $("#content").html(html);
                        } else {
                            $.messager.alert("错误", data.msg, "error");
                        }
                    }

                })
            }

            function analysisReturn(id) {
                $.messager.confirm("提示", "您确定重新分析退货逻辑吗？", function (flag) {
                    if (flag) {
                        $.ajax({
                            url: config.url + "/uploadRecord/analysisReturn/" + id,
                            type: "post",
                            xhrFields: {withCredentials: true},
                            beforeSend: function () {
                                $.messager.progress({
                                    title: "请稍等",
                                    interval: 50,
                                    text: "正在分析中..."
                                });
                            },
                            complete: function () {
                                $.messager.progress("close");
                            },
                            success: function (data) {
                                $.messager.alert("提示", data, "info");
                            },
                            error: function (data) {
                                $.messager.alert("提示", '分析退货逻辑失败', "info");
                                console.log(data);
                            }
                        })

                    }
                })
            }

            function stopImport(id) {
                $.messager.confirm("提示", "您确定要停止上传吗？(目前只针对旧上传方式)", function (flag) {
                    if (flag) {
                        $.ajax({
                            url: config.url + "/uploadRecord/stopUpload",
                            type: "post",
                            data: {id: id},
                            dataType: 'json',
                            xhrFields: {withCredentials: true},
                            beforeSend: function () {
                                $.messager.progress({
                                    title: "请稍等",
                                    interval: 30,
                                    text: "正在停止中..."
                                });
                            },
                            complete: function () {
                                $.messager.progress("close");
                            },
                            success: function (data) {
                                $.messager.alert("提示", data.msg, "info");
                            },
                            error: function () {
                                $.messager.alert("提示", '操作失败', "info");
                            }
                        })

                    }
                })
            }

            function reImport(id) {
                alert("暂时关闭");
                return;
                $.messager.confirm("提示", "您确定删除已导入记录，重新导入吗？", function (flag) {
                    if (flag) {
                        $.ajax({
                            url: config.url + "/uploadRecord/reImport/" + id,
                            type: "post",
                            data: {"delete": true},
                            xhrFields: {withCredentials: true},
                            success: function (data) {
                                $.messager.alert("提示", "设置重新导入成功", "info");
                            }
                        })

                    }
                })
            }
            function importAgain(id) {
                $.messager.confirm("提示", "您确定再次分析未匹配记录吗？", function (flag) {
                    if (flag) {
                        $.ajax({
                            url: config.url + "/uploadRecord/unMatch/" + id,
                            type: "post",
                            dataType:'json',
                            contentType:'application/json;charset=UTF-8',
                            xhrFields: {withCredentials: true},
                            beforeSend: function () {
                                $.messager.progress({
                                    title: "请稍等",
                                    interval: 30,
                                    text: "正在分析中..."
                                });
                            },
                            complete: function () {
                                $.messager.progress("close");
                            },
                            success: function (data) {
                                if (data.code == 200) {
                                    $.messager.alert("提示", data.msg, "info");
                                }else {
                                    $.messager.alert("提示", data.msg, "error");
                                }
                            }
                        })
                    }
                })
            }

            function disableOne(id) {
                $.messager.confirm("提示", "您确定删除该记录吗？", function (flag) {
                    if (flag) {
                        $.ajax({
                            url: config.url + "/uploadRecord/" + id,
                            type: "delete",
                            xhrFields: {withCredentials: true},
                            beforeSend: function () {
                                $.messager.progress({
                                    title: "请稍等",
                                    interval: 30,
                                    text: "数据加载中..."
                                });
                            },
                            success: function (data) {
                                $.messager.progress("close");
                                $.messager.alert("提示", "删除成功", "info", function () {
                                    searchBy();
                                });
                            }
                        })
                    }
                })
            }

            function downloadFile(id) {
                $.ajax({
                    url: config.url + "/uploadRecord/download/" + id,
                    type: "get",
                    xhrFields: {withCredentials: true},
                    success: function (data) {
                        if (data) {
                            window.location.href = data;
                        }
                    }
                })
            }

            function searchBy(page, size) {
                var data = getFormData(document.getElementById("ff"));
                data['page'] = page || 1;
                data['size'] = size || 100;
                $.ajax({
                    url: config.url + "/uploadRecord/page?dataReportCode=" + dataReportCode + "&channelCode=" + channelCode,
                    type: "get",
                    data: transfer(data),
                    xhrFields: {withCredentials: true},
                    beforeSend: function () {
                        $.messager.progress({
                            title: "请稍等",
                            interval: 50,
                            text: "数据加载中..."
                        });
                    },
                    complete: function () {
                        $.messager.progress("close");
                    },
                    success: function (data) {
                        $.messager.progress("close");
                        if (data) {
                            for (var i = 0; i < data.content.length; i++) {
                                var haha = (function (str) {
                                    var arr = str.split('/');
                                    return arr[arr.length - 1]
                                }(data.content[i].filePath));
                                data.content[i].filePath = haha;
                            }
                            $("#datagrid").datagrid("loadData", data);
                        }
                    },
                    error: function (data) {
                        console.log(data);
                    }
                });
            }

            function strHandle(str) {
                var arr = str.split('/');
                console.log();
                return arr[arr.length - 1]
            }

            function upload() {
                //上传阿里云文件
                $.ajax({
                    url: config.url + "/aliyun/getToken?dataReportId=" + id,
                    xhrFields: {withCredentials: true},
                    beforeSend: function () {
                        $.messager.progress({
                            title: "请稍等",
                            interval: 50,
                            text: "数据加载中..."
                        });
                    },
                    success: function (data) {
                        var client = new OSS({
                            region: data.region,
                            accessKeyId: data.accessKeyId,
                            accessKeySecret: data.accessKeySecret,
                            stsToken: data.stsToken,
                            bucket: data.bucket
                        });
                        // var file=$("input[type='file']")[0].files[0];
                        var filevalue = $("input[type='file']")[0].files.length;
                        async function putBlob(path) {
                            try {

                                var formlist = new Array();
                                for (var i = 0; i < filevalue; i++) {
                                    var file = $("input[type='file']")[0].files[i];
                                    var result = await client.put(path + file.name, file);
                                    var form = getFormData(document.getElementById("window-form"));
                                    form.dataReportCode = dataReportCode;
                                    form.filePath = result.name;
                                    formlist.push(form)
                                }

                                var uploadVersion = $("#uploadVersion").combobox("getValue");
                                var fileType = $("#fileType").combobox("getValue");
                                $("#w").window("close");
                                $.messager.progress("close");

                                $.ajax({
                                    url: config.url + "/uploadRecord/importExcel?uploadVersion=" + uploadVersion+"&fileType="+fileType,
                                    xhrFields: {withCredentials: true},
                                    contentType: 'application/json;charset=UTF-8',
                                    data: JSON.stringify(formlist),
                                    type: "POST",
                                    success: function (d) {
                                        //刷新上传任务
                                        refresh();
                                        //刷新列表
                                        searchBy();
                                    },
                                    error: function () {
                                        $.messager.progress("close");
                                    }
                                });

                            } catch (e) {
                                console.log(e);
                            }
                        }

                        putBlob(data.path);
                    },
                    error: function () {
                        $.messager.progress("close");
                    }
                })
            }

            function templateFormatter(val, row, index) {
                return row.template ? row.template.name : "没有模版";
            }

            function dateFormatter(date) {
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                if (m < 10) {
                    m = "0" + m;
                }
                var d = date.getDate();
                if (d < 10) {
                    d = "0" + d;
                }
                return y + '-' + m + '-' + d;
            }

            function dateParser(date) {

            }

            function importStatusFormatter(val, row) {
                if (val == "SUCCESS") {
                    return "<a class='l-btn-left l-btn-icon-left' style='width:24px;height:24px;'><span class='l-btn-icon icon-ok'></span></a>";
                }
                var colorType;
                switch (row.statusLevel) {
                    case 1:
                        colorType = "goldenrod";
                        break;
                    case 2:
                        colorType = "#4cae4c";
                        break;
                    case 3:
                        colorType = "red";
                        break;
                    default:
                        colorType = "#999999";

                }
                return "<span style='color: " + colorType + "'>" + row.statusDesc + "</span>";
            }

            function selectFile() {
                $("#w").window("open");
                $("#upload").filebox({
                    buttonText: "选择文件",
                    multiple: true

                });
                $.ajax({
                    url: config.url + "/template/findByChannelCode?channelCode=" + channelCode,
                    xhrFields: {withCredentials: true},
                    type: "get",
                    success: function (data) {
                        if (data) {
                            $("#template").combobox({
                                "textField": "name",
                                "valueField": "code",
                                "panelHeight": "auto",
                                "data": data
                            });
                        }
                    }
                });

            }

            function refresh() {
                $.ajax({
                    url: config.parseUrl + "/cron/import-parse/ec44c42f91ef4478b1c46838601788cb",
                    type: "GET",
                    xhrFields: {withCredentials: true},
                    success: function (d) {

                    },
                    error: function () {
                    }
                });
            }

            function dd(code) {
                $("#dd").window("open");
                $('#uploadRecordCode').textbox("setValue", code);
                var fruits = ["07","08","09","10","14","15"]
                $('#categoryList').combobox("setValues", fruits);


            }
            //根据品类条件删除文件下销售数据
            function removeCa() {
                var categoryList = $("#categoryList").combotree("getValues");//.toString()
                if((categoryList.length==1 && !categoryList[0]) ||categoryList.length==0){
                    $.messager.alert("错误","请选操作品类","error");
                    return;
                }

                $.messager.confirm("提示", "您确定要删除数据吗?删除品类为"+categoryList.toString(), function (r) {
                    var data = getFormData(document.getElementById("ff"));
                    data.categoryCode=categoryList.toString();
                    data.uploadRecordCode = $("#uploadRecordCode").textbox('getValue');
                    $.ajax({
                        url:config.url + "/emptyModel/removeCas",
                        type:"get",
                        data:transfer(data),
                        dataType: "json",
                        xhrFields:{withCredentials:true},
                        beforeSend:function () {
                            $.messager.progress({
                                title:"请稍等",
                                interval:50,
                                text:"数据加载中..."
                            });
                        },
                        success:function(data){
                            $.messager.progress("close");
                            if(data.code==200){
                                $.messager.alert("提示",data.msg,"info",function () {
                                    searchBy();
                                    $("#dd").window("close");
                                });
                            }else {
                                $.messager.alert("提示",data.msg,"error");
                            }
                        },
                        error:function(data){
                            console.log(data);
                            $.messager.progress("close");
                        }
                    });
                })
            }

            /**
             * 天猫去重 根据商场、原始型号、原量
             * @returns {boolean}
             */
            function tmReRepeat() {
                //datagrid重载默认值   getChecked获取勾选集合
                var selectedRow = $("#datagrid").datagrid("getChecked");
                if (selectedRow != null && selectedRow.length > 1) {
                    var codes = selectedRow.map(function (item) {
                        return item.code;
                    });
                    $.messager.confirm("提示", "您确定删除其中的重复数据吗?", function (r) {
                        if (r) {
                            $.ajax({
                                url: config.url + "/uploadRecord/tmReRepeat",
                                type: 'POST',
                                xhrFields: {withCredentials: true},
                                dataType: 'json',
                                contentType: 'application/json;charset=UTF-8',
                                data: JSON.stringify(codes),
                                success: function (codes) {
                                    $.messager.alert("提示", "操作成功", "info", function () {
                                        searchBy(1, 100);
                                    });
                                },
                                error: function (XMLHttpRequest, textStatus, thrown) {

                                }
                            });
                        }
                    });
                } else {
                    $.messager.alert("提示", "请选择相关记录，至少两条", "error");
                    return false;
                }
            }

            function retryDate(code){
                $.ajax({
                    url: config.parseUrl + "/date-format/upload-file-retry/" + code,
                    type: "POST",
                    // xhrFields: {withCredentials: true},
                    headers: {'Authorization': sessionStorage.getItem('Authorization')},
                    beforeSend: function () {
                        $.messager.progress({
                            title: "请稍等",
                            interval: 20,
                            text: "数据操作中..."
                        });
                    },
                    complete: function () {
                        $.messager.progress("close");
                    },
                    success: function (result) {
                        if (result.code == 0) {
                            $.messager.alert("提示", "操作完成！共识别"+result.data+"条", "info", function () {
                                searchBy();
                            });
                        }else {
                            $.messager.alert("提示", result.msg, "error");
                        }
                    },
                    error: function () {
                    }
                });
            }

            function cancelWarn(code){
                $.messager.confirm("提示", "您确定要撤销异常吗?", function (r) {
                    $.ajax({
                        url:config.url + "/uploadRecord/cancelWarn/"+code,
                        type:"post",
                        xhrFields:{withCredentials:true},
                        beforeSend:function () {
                            $.messager.progress({
                                title:"请稍等",
                                interval:50,
                                text:"数据加载中..."
                            });
                        },
                        success:function(data){
                            $.messager.progress("close");
                            if(data.code==200){
                                $.messager.alert("提示",data.msg,"info",function () {
                                    searchBy();
                                });
                            }else {
                                $.messager.alert("提示",data.msg,"error");
                            }
                        },
                        error:function(data){
                            console.log(data);
                            $.messager.progress("close");
                        }
                    });
                })
            }
        </script>
    </body>
</html>